package com.voja.salonschedule.customers;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.voja.AndroidUtils.Application;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;

public class TmpFile {
    
    public static final String TMP_FILENAME = "salonschedule.jpg";
    
    private String   type;
    private File     file;
    private FileOutputStream fos;
    
    private static TmpFile _instance;
    public static TmpFile getInstance(Context context, String type) {
        if (_instance == null) {
            _instance = new TmpFile(context, type);
        }
        
        return _instance;
    }
    
    public TmpFile(Context context, String type) {
        this.type    = type;
    }
    
    public File create() {
        file = new File(getAbsolutePath());
        try {
            if (! file.exists()) {
                file.setWritable(true, false);
                file.setReadable(true, false);
                file.createNewFile();
            }
        } catch (IOException e) {
            Application.alert("IO: " + e.getMessage());
        }
        
        return file;
    }
    
    public void createOutputStream() throws IOException {
        if (fos == null || !fos.getFD().valid()) {
            fos = new FileOutputStream(file);
        }
    }
    
    public boolean delete() {
        if (file == null) {
            create();
        }
        return file.delete();
    }
    
    public String getAbsolutePath() {
        File dir = Environment.getExternalStoragePublicDirectory(type);
        return dir.getAbsolutePath() + File.separator + TMP_FILENAME;
    }
    
    public void write(byte[] data) {
        create();
        try {
            createOutputStream();
            fos.write(data);
            fos.close();
        } catch (IOException e) {
            Application.alert("IO: " + e.getMessage());
        }
    }
    
    public File getFile() {
        if (file == null) {
            create();
        }
        return file;
    }
    
    public Uri getUri() {
        return Uri.fromFile(getFile());
    }
    
    public FileOutputStream getOutStream() {
        return fos;
    }
    
    public void copyFromFile(File file) throws IOException {
        FileInputStream     fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        int size     = (int)file.length();
        byte[] bytes = new byte[size];
        bis.read(bytes, 0, bytes.length);
        bis.close();
        
        write(bytes);
    }
    
    public void closeOutStream() throws IOException {
        fos.close();
    }
    
}
